<template>
 <div>
    <a-tabs :activeKey="defKey" @change="callback">
      <a-tab-pane key="1" tab="设备属性">
        <a-spin :spinning="confirmLoading">
            <j-form-container :disabled="formDisabled">
              <a-form :form="form" slot="detail" style="height: 500px; overflow: auto">
                <a-row>
                  <a-col :span="24">
                    <a-form-item label="设备编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['eqpNo',validatorRules.eqpNo]" placeholder="请输入设备编号"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['name',validatorRules.name]" placeholder="请输入设备名称"></a-input>
                    </a-form-item>
                  </a-col>

                  <a-col :span="24">
                    <a-form-item label="类名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['typename']" placeholder="请输入类名"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['supplier_dictText']" placeholder="请输入供应商" style="float: left; width: 400px"></a-input>
                      <a-button @click="showModal" type="primary" icon="search" style="float: left; margin-left: 10px">选择</a-button>
                    </a-form-item>
                  </a-col>

                  <a-col :span="24">
                    <a-form-item label="平均故障间隔时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['mtbf']" placeholder="请输入平均故障间隔时间"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="平均维修时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['mttr']" placeholder="请输入平均维修时间"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="重量" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-decorator="['weight']" placeholder="请输入重量"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="长" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input-number v-decorator="['length']" placeholder="请输入长" style="width: 100%"/>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="宽" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input-number v-decorator="['width']" placeholder="请输入宽" style="width: 100%"/>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="高" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input-number v-decorator="['height']" placeholder="请输入高" style="width: 100%"/>
                    </a-form-item>
                  </a-col>

                  <a-col :span="24">
                              <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                                <a-textarea v-decorator="['memo']" rows="4" placeholder="请输入备注"/>
                              </a-form-item>
                            </a-col>
                  <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                    <a-button @click="submitForm">提 交</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </j-form-container>

            <!-- 弹窗 供应商 -->
            <a-modal v-model="visibleModal" title="供应商" :width="gysWidth" @ok="handleOk" @cancel="handelCancel">
              <a-table
                bordered
                rowKey="name"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type:'radio' }"
                :columns="innerColumns"
                :data-source="dataSource"
                :scroll="{ y: 240 }"
              />
            </a-modal>

          </a-spin>
      </a-tab-pane>
      <a-tab-pane key="2" tab="文件信息" force-render>
         <a-button @click="getFileModal" type="primary" icon="plus">选择已有文件</a-button>

        <!--<j-upload v-model="fileList" text="上传" @change="handleChange"></j-upload>-->
        <DtgUploadFile @changeFile="handleChange"></DtgUploadFile>

         <a-table rowKey="id" :columns="columnsTab" :data-source="dataTab" style="margin-top: 20px">
           <span slot="action" slot-scope="text, record">
            <a @click="handleDel(record)"><a-icon type="minus-circle" /> 删除</a>
          </span>
         </a-table>

      </a-tab-pane>
    </a-tabs>


    <!-- 已有文件弹窗 -->
     <a-modal v-model="FileModalVisible" title="选择已有文件" @ok="FileModalOk" width="800px">
       <a-input placeholder="请输入文件名" v-model="fileName" style="width: 240px" />
       <a-button type="primary" @click="searchFile" icon="search" style="margin-left: 18px">查询</a-button>
       <a-table
         style="margin-top: 15px;"
         bordered
         rowKey="id"
         :row-selection="{ selectedRowKeys: selectedFileRowKeys, onChange: onSelectFileChange }"
         :columns="columnsFile"
         :data-source="dataFile"
       />
     </a-modal>
  </div>

</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import { loadCategoryData } from '@/api/api'
  import { fileDetailsInfoGetByPid,getFileDetailsInfoList,getFileDetailsList,fileTransManageAdd,fileTransManageDelete } from '@/api/digitization'
  import JUpload from '@/components/jeecg/JUpload'
  import DtgUploadFile from './DtgUploadFile'

  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"

  export default {
    name: 'DtgEquipmentInfoForm',
    components: {
      JFormContainer,JUpload,DtgUploadFile
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        defKey: '1',
        headers: {
          authorization: 'authorization-text',
        },
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          eqpNo: {
            rules: [
              { required: true, message: '请输入设备编号!'},
            ]
          },
          name: {
            rules: [
              { required: true, message: '请输入设备名称!'},
            ]
          },
        },
        url: {
          add: "/base/dtgEquipmentInfo/add",
          edit: "/base/dtgEquipmentInfo/edit",
          queryById: "/base/dtgEquipmentInfo/queryById",
          querygys:"/base/dtgSupplierInfo/list",
        },

        tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        // action: window._CONFIG['domianURL']+"/sys/common/upload",
        innerColumns:[
          {
            title: '供应商名称',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '类名',
            dataIndex: 'typeName',
            key: 'typeName',
          },
          {
            title: '备注',
            dataIndex: 'memo',
            key: 'memo',
            ellipsis: true,
          },

        ],
        dataSource:this.getTable(),
        visibleModal: false,
        selectedRowKeys: ['1'],
        loading: false,
        gysWidth: 700,
        currentRow:{},
        columnsTab:[
          {
            title: '文件名',
            dataIndex: 'fileTitle',
            key: 'fileTitle',
          },
          {
            title: '编号',
            dataIndex: 'fileCode',
            key: 'fileCode',
          },
          {
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
          },
          {
            title: '格式',
            dataIndex: 'fileTypes',
            key: 'fileTypes',
          },
          {
            title: '大小',
            dataIndex: 'fileSize',
            key: 'fileSize',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {customRender: 'action'}
          }
        ],
        dataTab:[],
        FileModalVisible: false,
        // selectedFileRowKeys:['3g69ummitotnrrfnj46eihak7vu3egkk'],    //默认选中
        selectedFileRowKeys:[],
        selectedFileList: [],
        columnsFile:[
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'创建人',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'创建日期',
            align:"center",
            dataIndex: 'createTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'编号',
            align:"center",
            dataIndex: 'fileCode'
          },
          {
            title:'文件名',
            align:"center",
            dataIndex: 'fileTitle'
          },
          {
            title:'编制单位',
            align:"center",
            dataIndex: 'orgBelong'
          },
          {
            title:'文档格式',
            align:"center",
            dataIndex: 'fileTypes'
          },
        ],
        dataFile:[],
        fileList:[],
        userInfo: this.$store.getters.userInfo,
        fileName:''


      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      },
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      callback(key) {
        this.defKey = key;
      },
      getTable(){
        getAction('/base/dtgSupplierInfo/list').then(res => {
          this.dataSource = res.result.records;
        });
      },
      showModal(){
        this.visibleModal = true;
      },
      handleOk(e) {
        this.visibleModal = false;
      },
      handelCancel(){
        this.handleOk();
      },
      onSelectChange(selectedRowKeys,row){
        this.selectedRowKeys = selectedRowKeys;
        this.currentRow = row[0];
        this.$nextTick(() => {
          this.form.setFieldsValue(pick({'supplier_dictText':row[0].name},'supplier_dictText'))
        })

      },
      add () {
        this.edit({});
        this.defKey = '1';
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'eqpNo','name','memo','typename','mtbf','mttr','weight','length','width','height'))

          this.form.setFieldsValue(pick({'supplier_dictText':record.supplier_dictText},'supplier_dictText'))
        })

        //获取文件信息table数据
        this.getfileDetailsInfo(record.id);

      },
      getfileDetailsInfo(pid){
        let params = {
          pid
        }
        fileDetailsInfoGetByPid(params).then(res => {
          if(res.result && res.result.length){
            this.dataTab = res.result;
          }
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      //选中已有文件弹窗
      getFileModal(){
        this.fileName = '';
        this.FileModalVisible = true;
        getFileDetailsInfoList().then(res => {
          this.dataFile = res.result.records;
        })
      },
      searchFile(){
        getFileDetailsInfoList({fileTitle: '*'+this.fileName+'*'}).then(res => {
          this.dataFile = res.result.records;
        })
      },
      FileModalOk(){
        this.FileModalVisible = false;

        this.selectedFileList.forEach(opt => {
          let {id,createBy,fileCode,fileTitle,fileTypes,fileSize} = opt;
          let obj = {};
          obj = {
            id,
            fileTitle,
            fileCode,
            createBy,
            fileTypes,
            fileSize,
          };
          this.dataTab.push(obj);
        })
        let hash = {};
        this.dataTab = this.dataTab.reduceRight((item, next) => {
          hash[next.id] ? '' : hash[next.id] = true && item.push(next);
          return item
        }, []);

      },
      onSelectFileChange(selectedRowKeys,row){
        this.selectedFileRowKeys = selectedRowKeys;
        this.selectedFileList = row;
      },

      handleChange(info) {
        let {name,uid,type,size} = info.file;
        let obj = {};
        obj = {
          id: uid,
          fileTitle: name,
          fileCode: uid,
          createBy: this.userInfo.realname,
          fileTypes: type,
          fileSize: size,
        }
        this.dataTab.push(obj);

        this.uploadFile(info);
      },
      uploadFile(info){
        let {createBy,createTime,updateBy,updateTime,orgCode} = this.userInfo;
        let {id,name} = this.model;
        let {uid,size} = info.file;
        let fileType = info.file.name.split('.')[1]
        let fileTitle = info.file.name;
        let fileMixName = info.file.response.message.split('/')[1];
        let filePath = info.file.response.message;

        let params = {};
        let obb = {};
        let obj = {};

        obb = {
          id:'',
          createBy,
          createTime,
          updateBy,
          updateTime,
          sysOrgCode:orgCode,
          fileCode:uid,
          fileTitle,
          eqpBelong:name,
          filePath,
          fileMixName,
          fileTypes: fileType,
          fileSize: size,
          pid: id,
          modelName:'设备管理',
          eqpUid: id
        };

        obj = {
          id,
          createBy,
          createTime,
          updateBy,
          updateTime,
          sysOrgCode:orgCode,
          versionNo:'1.0',
        };

        params = {
          obj,
          obb
        }

        fileTransManageAdd(params).then(res => {
          if(res.success){
            this.$message.success(`${info.file.name} 上传成功!`);
          }else{
            this.$message.warning(`${info.file.name} ${res.message}`);
          }
        })
      },

      initTab(){
        this.dataTab = [];
        this.defKey = '1';
      },
      handleDel(item){
        let that = this;
        console.log(item)
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            fileTransManageDelete({ids:item.id+","}).then((res) => {
              if (res.success) {
                //删除列表文件
                let idx = that.dataTab.findIndex(opt => opt.id === item.id);
                that.dataTab.splice(idx,1);
                //删除已有文件的选中状态
                let i = that.selectedFileRowKeys.findIndex(opt => opt.id === item.id);
                that.selectedFileRowKeys.splice(i,1);
                that.$message.success(res.message);
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            debugger;

            formData.supplier = this.currentRow.id;
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(this.model,'eqpNo','name','memo','typename','mtbf','mttr','weight','length','width','height'))
      },
    }
  }
</script>